#include "IOUringEventLoopThread.h"
#include "IOUringEventLoop.h"
#include "Logger.h"

using namespace std::placeholders;

IOUringEventLoopThread::IOUringEventLoopThread(int acceptFd,
                                               const ThreadInitCallback &cb,
                                               const std::string &name)
    : loop_(nullptr), exiting_(false),
      thread_(std::bind(&IOUringEventLoopThread::threadFunc, this), name),
      acceptFd_(acceptFd), mutex_(), cond_(), callback_(cb) {}

IOUringEventLoopThread::~IOUringEventLoopThread() {
    exiting_ = true;
    if (loop_ != nullptr) {
        loop_->quit();
        thread_.join();
    }
}

IOUringEventLoop *IOUringEventLoopThread::startLoop() {
    thread_.start(); // 启动底层的线程
    IOUringEventLoop *loop = nullptr;
    {
        std::unique_lock<std::mutex> lock(mutex_);
        while (loop_ == nullptr) {
            cond_.wait(lock);
        }
        loop = loop_;
    }
    return loop;
}
// 在单独的新线程中运行
void IOUringEventLoopThread::threadFunc() {
    // 创建一个EventLoop, 与 thread_ 一一对应, one loop per thread
    IOUringEventLoop loop(acceptFd_);
    LOG_DEBUG("new thread start");
    if (callback_) {
        callback_(&loop);
    }

    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }

    loop.setNewConnectionCallback(std::bind(newConnectionCallback_, &loop, _1));
    loop.setReadCompleteCallback(std::bind(readCompleteCallback_, &loop, _1));
    loop.setWriteCompleteCallback(std::bind(writeCompleteCallback_, &loop, _1));
    loop.addProvideBufAll();
    loop.loop();
    std::unique_lock<std::mutex> lock(mutex_);
    loop_ = nullptr;
}
